package start.log;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OperateLogService {

    enum ActionEnum{
        ADD("新建"),
        UPDATE("修改"),
        DELETE("删除");

        ActionEnum(String desc) {
            this.desc = desc;
        }
        public String desc;
    }





    public <T> void saveLog(String operatorId, Long bizId, Integer bizType, T target, T original){
        if(StringUtils.isBlank(operatorId) || (Objects.isNull(target) && Objects.isNull(original))){
            throw new IllegalArgumentException();
        }
        if(Objects.nonNull(target) && Objects.nonNull(original) && !target.getClass().isAssignableFrom(original.getClass())){
            throw new IllegalArgumentException();
        }
        ActionEnum action = getAction(target, original);
        List<Triple<String, String, LogField>> changeInfos = getChangeInfoList(target, original);
        List<String> changeInfoList = new ArrayList<>();
        if(CollectionUtils.isEmpty(changeInfos) && !ActionEnum.UPDATE.equals(action)){
            changeInfoList.add(0, action.desc);
        }else if (CollectionUtils.isEmpty(changeInfos)){
            return;
        }else {
            changeInfoList = changeInfos.stream().map(i -> i.getRight().spliceValue() ?
                            action.desc + StringUtils.joinWith("为:", i.getLeft(), i.getMiddle()) :
                            action.desc + StringUtils.join("了", i.getLeft()))
                    .collect(Collectors.toList());
        }

        String operateContext = StringUtils.join(changeInfoList, "\n");
        operateContext = operateContext.replaceAll("\"","")
                .replaceAll("\\[","").replaceAll("\\]","");
        CommonOperatorLog operatorLog = new CommonOperatorLog();
        operatorLog.setBizId(bizId);
        operatorLog.setBizType(bizType);
        operatorLog.setOperateContent(operateContext);
        operatorLog.setOperatorId(operatorId);
        operatorLog.setChangeBefore(JSON.toJSONString(original));
        operatorLog.setChangeAfter(JSON.toJSONString(target));

        log.info("操作日志：{}", operatorLog);
    }

    private ActionEnum getAction(Object target, Object original){
        ActionEnum action = ActionEnum.ADD;
        if(Objects.nonNull(target) && Objects.nonNull(original)){
            action = ActionEnum.UPDATE;
        }else if(Objects.nonNull(target)){
            action = ActionEnum.ADD;
        }else if (Objects.nonNull(original)){
            action = ActionEnum.DELETE;
        }
        return action;
    }


    private<T> List<Triple<String, String, LogField>> getChangeInfoList(T target, T original){
        if(Objects.isNull(target) || Objects.isNull(original)){
            return new ArrayList<>();
        }
        List<Pair<Field, Object>> targetFields = allFields(target);
        List<Pair<Field, Object>> originalFields = allFields(original);
        if(targetFields.size() != originalFields.size()){
            //理论上不可能执行到这
            throw new IllegalArgumentException();
        }

        List<Triple<String, String, LogField>> result = new ArrayList<>();
        for (int i = 0; i < targetFields.size(); i++) {
            Pair<Field, Object> targetField = targetFields.get(i);
            Pair<Field, Object> originalField = originalFields.get(i);
            ReflectionUtils.makeAccessible(targetField.getKey());
            ReflectionUtils.makeAccessible(originalField.getKey());
            Object targetValue = ReflectionUtils.getField(targetField.getKey(), targetField.getValue());
            Object originalValue = ReflectionUtils.getField(originalField.getKey(), originalField.getValue());
            if(targetValue != originalValue && (Objects.isNull(targetValue) ||
                    (!targetValue.equals(originalValue) &&
                            compareTo(Pair.of(targetField.getKey(), targetValue), Pair.of(originalField.getKey(), originalValue)) &&
                            !JSON.toJSONString(targetValue).equals(JSON.toJSONString(originalValue))))){
                result.add(Triple.of(getFieldName(targetField.getKey()), getFieldValue(targetField.getKey(), targetField.getValue()), targetField.getKey().getAnnotation(LogField.class)));
            }
        }
        return result;
    }

    private boolean compareTo(Pair<Field, Object> targetField, Pair<Field, Object> originalField){
        Field field = targetField.getKey();
        Object targetValue = targetField.getValue();
        Object originalValue = originalField.getValue();
        boolean canCompare = Arrays.stream(field.getType().getInterfaces()).anyMatch(i -> Comparable.class.getName().equals(i.getName()));
        if(canCompare && Objects.nonNull(targetValue) && Objects.nonNull(originalValue)){
            Method compareTo = ReflectionUtils.findMethod(field.getType(), "compareTo", field.getType());
            if(Objects.isNull(compareTo)){
                return true;
            }
            Object compared = ReflectionUtils.invokeMethod(compareTo, targetValue, originalValue);
            return (int)compared != 0 ;
        }
        return true;
    }

    private <T> List<Pair<Field, Object>> allFields(T obj){
        List<Triple<Field, Object, Boolean>> targetField = findField(obj);
        List<Triple<Field, Object, Boolean>> allField = Lists.newArrayList(targetField);
        List<Triple<Field, Object, Boolean>> needRemove = new ArrayList<>();
        for (int i = 0; i < allField.size(); i++) {
            Triple<Field, Object, Boolean> fieldObjectDes = allField.get(i);
            if(!fieldObjectDes.getRight()){
                ReflectionUtils.makeAccessible(fieldObjectDes.getLeft());
                Object fieldV = ReflectionUtils.getField(fieldObjectDes.getLeft(), fieldObjectDes.getMiddle());
                List<Triple<Field, Object, Boolean>> fieldList = findField(fieldV);
                if(!CollectionUtils.isEmpty(fieldList)){
                    allField.addAll(fieldList);
                    needRemove.add(fieldObjectDes);
                }
            }
        }

        if(!CollectionUtils.isEmpty(needRemove)){
            allField.removeAll(needRemove);
        }
        return allField.stream().map(i->Pair.of(i.getLeft(), i.getMiddle())).collect(Collectors.toList());
    }

    private <T> List<Triple<Field, Object, Boolean>> findField(T obj){
        Class<?> objClass = obj.getClass();
        Field[] declaredFields = objClass.getDeclaredFields();
        List<Field> allFields = Lists.newArrayList(declaredFields);
        if(Objects.nonNull(objClass.getSuperclass())){
            Field[] superClassFields = objClass.getSuperclass().getDeclaredFields();
            allFields.addAll(Arrays.asList(superClassFields));
        }
        List<Triple<Field, Object, Boolean>> result = new ArrayList<>();
        for (Field declaredField : allFields) {
            LogField annotation = declaredField.getAnnotation(LogField.class);
            if(Objects.nonNull(annotation)){
                result.add(Triple.of(declaredField, obj, declaredField.getType().getPackage().getName().startsWith("java")));
            }
        }
        return result;
    }


    private String getFieldName(Field field){
        LogField annotation = field.getAnnotation(LogField.class);
        String name = annotation.name();
        if(StringUtils.isBlank(name)){
            name = field.getName();
        }
        return name;
    }

    private <T> String getFieldValue(Field field, T targetObj){
        LogField annotation = field.getAnnotation(LogField.class);
        if(!annotation.spliceValue()){
            return "";
        }
        String valueFun = annotation.valueFun();
        if(StringUtils.isBlank(valueFun)){
            Object fieldValue = ReflectionUtils.getField(field, targetObj);
            return getStrValue(fieldValue);
        }else {
            Method valueMethod = ReflectionUtils.findMethod(targetObj.getClass(), valueFun);
            if(Objects.isNull(valueMethod)){
                Object fieldValue = ReflectionUtils.getField(field, targetObj);
                return getStrValue(fieldValue);
            }else {
                ReflectionUtils.makeAccessible(valueMethod);
                Object invokeMethodRes = ReflectionUtils.invokeMethod(valueMethod, targetObj);
                return getStrValue(invokeMethodRes);
            }
        }
    }

    private String getStrValue(Object fieldValue){
        List<String> emptyStr = ImmutableList.of("\"\"", "{}","[]");
        String value = Objects.isNull(fieldValue) ? "无" : JSON.toJSONString(fieldValue);
        return emptyStr.contains(value) ? "无" : value;
    }
}